package john.walker.spi;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Properties;

import john.walker.ProxyConnection;

/**
 * @author 30san
 *
 */
public class MysqlProxyDriver extends com.mysql.jdbc.Driver {

	static {
		try {
			Enumeration<Driver> drivers = DriverManager.getDrivers();
			while(drivers.hasMoreElements()) {
				Driver driver = drivers.nextElement();
				if(com.mysql.jdbc.Driver.class.isAssignableFrom(driver.getClass())) {
					DriverManager.deregisterDriver(driver);
				}
			}
			DriverManager.registerDriver(new john.walker.spi.MysqlProxyDriver());
		} catch (SQLException e) {
			// do not care this exception
		}
	}

	public MysqlProxyDriver() throws SQLException {
		super();
	}

	@Override
	public Connection connect(String url, Properties info) throws SQLException {
		return new ProxyConnection(super.connect(url, info));
	}

	/*@Override
	public Properties parseURL(String url, Properties info) throws SQLException {
		Properties defaultProp = super.parseURL(url, info);
		String configNames = defaultProp.getProperty("config");
		if (configNames != null) {
			InputStream configAsStream = null;
			try {
				configAsStream = getClass().getResourceAsStream("/configs/" + configNames + ".properties");
				if(configAsStream != null) {
    				Properties props = new Properties();
    				props.load(configAsStream);
    				defaultProp.putAll(props);
				}
			} catch (IOException ioEx) {
				throw new SQLException(ioEx);
			} finally {
				if(configAsStream!=null) {
					try {
						configAsStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return defaultProp;
	}*/
}
